//
//  SecondViewController.swift
//  swiftTS
//
//  Created by 航电 on 2020/3/2.
//  Copyright © 2020 航电. All rights reserved.
//

import UIKit
import MapKit
import CoreLocation

class SecondViewController: UIViewController {

    var mapView : MKMapView!;
    let screenSize = UIScreen.main.bounds.size;

    //显示地图中心点
    var coordinateCenter = CLLocationCoordinate2DMake(32.029171, 118.788231);
    var coordinatdTitle = "南京夫子庙";
    var coordinatdSubTitle = "南京市秦淮区秦淮河北岸中华路";
    var annationArray = NSMutableArray();
    
    //定位
    let coreLocationManager = CLLocationManager();
    
    lazy var showView:SecondView = {
        let showView = SecondView();
        return showView;
    }();
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "MapKit使用"
        self.view.backgroundColor = UIColor.white;
        // Do any additional setup after loading the view.
        self.onCreateUIForNavigation();
        self.onCreatUIForView();
        
        self.onGetLocalLocation();
    }
    
    //TODO:创建UI
    func onCreateUIForNavigation() {
        let backItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(backAction));
        self.navigationItem.leftBarButtonItem = backItem;
        
        self.navigationController?.navigationBar.barTintColor = .yellow;
        
        //设备背景图片barTintColor就无效
//        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default);
        
        let rightChangeItem = UIBarButtonItem(title: "选择地址", style: .plain, target: self, action: #selector(onChangeCoordinateAction));
        self.navigationItem.rightBarButtonItem = rightChangeItem;
    }

    func onCreatUIForView() {
        mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height));
        mapView.delegate = self;
        //地图类型
        mapView.mapType = .standard;
        mapView.showsBuildings = true;
        //显示位置
        mapView.showsUserLocation = true;
        self.view.addSubview(mapView);
        
//        //设置地图距离中心点的范围，越小越精准
//        let coordinateSpan = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05);
//        let coordinateRegion = MKCoordinateRegion(center: coordinateCenter, span: coordinateSpan);
//        //显示区域
//        mapView.setRegion(coordinateRegion, animated: true);
//        
//        //添加大头针
//        let mapAnnotation = MKPointAnnotation();
//        mapAnnotation.coordinate = coordinateCenter;
//        mapAnnotation.title = coordinatdTitle;
//        mapAnnotation.subtitle = coordinatdSubTitle;
//        annationArray.add(mapAnnotation);
//        
//        mapView.addAnnotations(annationArray as! [MKAnnotation]);
//        mapView.showAnnotations(annationArray as! [MKAnnotation], animated: true);
        
        self.view.addSubview(self.showView);
        self.showView.callBackBlock { (data) in
            self.onSelectCoordinatedAction(data: data);
        };
    }
    
    //TODO:Actions
    //TODO:Private Actions
    @objc func backAction() {
        self.navigationController?.dismiss(animated: true, completion: nil);
    }
    
    func onSelectCoordinatedAction(data: [String:String]) {
        
        coordinateCenter = CLLocationCoordinate2DMake(Double(data["latitude"]!)!, Double(data["longitude"]!)!);
        coordinatdTitle = data["title"]!;
        coordinatdSubTitle = data["subTitle"]!;
        
        self.onChangeUIForMapView();
    }
    
    func onChangeUIForMapView() {
        //设置地图距离中心点的范围，越小越精准
        let coordinateSpan = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05);
        let coordinateRegion = MKCoordinateRegion(center: coordinateCenter, span: coordinateSpan);
        //显示区域
        mapView.setRegion(coordinateRegion, animated: true);
        
        //添加大头针
        let mapAnnotation = MKPointAnnotation();
        mapAnnotation.coordinate = coordinateCenter;
        mapAnnotation.title = coordinatdTitle;
        mapAnnotation.subtitle = coordinatdSubTitle;
        
        mapView.removeAnnotations(annationArray as! [MKAnnotation]);
        annationArray.removeAllObjects();
        
        annationArray.add(mapAnnotation);
        mapView.addAnnotations(annationArray as! [MKAnnotation]);
        mapView.showAnnotations(annationArray as! [MKAnnotation], animated: true);
    }
    
    func onGetLocalLocation() {
//        coreLocationManager.desiredAccuracy = .
        coreLocationManager.requestWhenInUseAuthorization();
    }
    
    //TODO:Public Actions
    @objc func onChangeCoordinateAction() {
        self.showView.onShow();
    }
}

//TODO:Map Delegate
extension SecondViewController:MKMapViewDelegate {
    
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        let reIdentifier = "second_pin";
        var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reIdentifier);
        if pinView == nil {
            pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reIdentifier);
            pinView?.image = UIImage(named: "bg_calendar_date");
            //大头针中心点偏移量
            pinView?.centerOffset = CGPoint(x: 0, y: 0);
            //大头针弹框显示
            pinView?.canShowCallout = true;
            //大头针弹框偏移量
            pinView?.calloutOffset = CGPoint(x: 0, y: 0);
            
            //设置大头针弹框左侧试图
            let leftImgView = UIImageView(frame: CGRect(x: 0, y: 0, width: 38, height: 44));
            leftImgView.image = UIImage(named: "watch_scanner_fragment_icon");
            pinView?.leftCalloutAccessoryView = leftImgView;
            
        } else {
            pinView?.annotation = annotation;
        }
        return pinView;
    }
    
    func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
        print("地图缩放级别发送改变时")
    }
     
    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        print("地图缩放完毕触法")
    }
     
    func mapViewWillStartLoadingMap(_ mapView: MKMapView) {
        print("开始加载地图")
    }
     
    func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
        print("地图加载结束")
    }
     
    func mapViewDidFailLoadingMap(_ mapView: MKMapView, withError error: Error) {
        print("地图加载失败")
    }
     
    func mapViewWillStartRenderingMap(_ mapView: MKMapView) {
        print("开始渲染下载的地图块")
    }
     
    func mapViewDidFinishRenderingMap(_ mapView: MKMapView, fullyRendered: Bool) {
        print("渲染下载的地图结束时调用")
    }
     
    func mapViewWillStartLocatingUser(_ mapView: MKMapView) {
        print("正在跟踪用户的位置")
    }
     
    func mapViewDidStopLocatingUser(_ mapView: MKMapView) {
        print("停止跟踪用户的位置")
    }
     
    func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
        print("更新用户的位置")
        let updateLocal = userLocation.location;
        if (updateLocal?.isKind(of: CLLocation.self))! {
            coordinateCenter = updateLocal!.coordinate;
            coordinatdTitle = userLocation.title ?? "";
            coordinatdSubTitle = userLocation.subtitle ?? "";
            
            self.onChangeUIForMapView();
        }
    }
     
    func mapView(_ mapView: MKMapView, didFailToLocateUserWithError error: Error) {
        print("跟踪用户的位置失败")
    }
     
    func mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode,
                 animated: Bool) {
        print("改变UserTrackingMode")
    }
     
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay)
        -> MKOverlayRenderer {
        print("设置overlay的渲染")
        return MKPolylineRenderer()
    }
     
    private func mapView(mapView: MKMapView,
                         didAddOverlayRenderers renderers: [MKOverlayRenderer]) {
        print("地图上加了overlayRenderers后调用")
    }
     
    /*** 下面是大头针标注相关 *****/
    func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
        print("添加注释视图")
    }
     
    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView,
                 calloutAccessoryControlTapped control: UIControl) {
        print("点击注释视图按钮")
    }
     
    func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
        print("点击大头针注释视图")
    }
     
    func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
        print("取消点击大头针注释视图")
    }
     
    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView,
                 didChange newState: MKAnnotationView.DragState,
                 fromOldState oldState: MKAnnotationView.DragState) {
        print("移动annotation位置时调用")
    }
}
